package com.minsu.mapper;

import com.minsu.entity.Fuel;
import com.minsu.entity.ProductionOrder;
import com.minsu.entity.ProductionOrderDetail;
import org.apache.ibatis.annotations.*;

import java.util.Date;
import java.util.List;

@Mapper
public interface ProductionOrdersMapper {


    @Select("SELECT COUNT(*) FROM production_orders")
    Long countAll();

    // 分页查询数据（保持原有 SQL 和映射配置）
    @Results({
            @Result(property = "orderId", column = "order_id"),
            @Result(property = "productionOrderNo", column = "production_order_no"),
            @Result(property = "batchNo", column = "batch_no"),
            @Result(property = "meltingTemperature", column = "melting_temperature"),
            @Result(property = "inoculantAmount", column = "inoculant_amount"),
            @Result(property = "pouringTemperature", column = "pouring_temperature"),
            @Result(property = "qualificationRate", column = "qualification_rate"),
            @Result(property = "productionTime", column = "production_time"),
            @Result(property = "inTime", column = "in_time"),
            @Result(property = "createdAt", column = "created_at"),
            @Result(property = "updatedAt", column = "updated_at"),
            @Result(
                    property = "details",
                    column = "order_id",
                    many = @Many(select = "com.minsu.mapper.ProductionOrdersMapper.findDetailsByOrderId")
            )
    })
    @Select("SELECT po.*, pod.batch_no, pod.material_ratio " +
            "FROM production_orders po " +
            "LEFT JOIN production_order_details pod ON po.order_id = pod.order_id " +
            "ORDER BY po.updated_at DESC LIMIT #{offset}, #{pageSize}")
    List<ProductionOrder> findAll(@Param("offset") Integer offset, @Param("pageSize") Integer pageSize);

    // 子查询：查询订单详情（保持原有方法）
    @Select("SELECT * FROM production_order_details WHERE order_id = #{orderId}")
    List<ProductionOrderDetail> findDetailsByOrderId(Integer orderId);


    //    @Insert("INSERT INTO production_orders (" +
//            "  production_order_no, melting_temperature, inoculant_amount, " +
//            "  pouring_temperature, qualification_rate, production_time, " +
//            "  batch_no, in_time, " +
//            "  created_at, updated_at" +
//            ") VALUES (" +
//            "  #{productionOrderNo}, #{meltingTemperature}, #{inoculantAmount}, " +
//            "  #{pouringTemperature}, #{qualificationRate}, #{productionTime}, " +
//            "  #{batchNo}, #{inTime}, " +
//            "  NOW(), NOW()" +
//            ")")
//    @Options(useGeneratedKeys = true, keyProperty = "orderId")
//    void add(ProductionOrder productionOrder);
    @Insert("INSERT INTO production_orders (" +
            "  production_order_no, melting_temperature, inoculant_amount, " +
            "  pouring_temperature, qualification_rate, production_time, " +
            "  batch_no, in_time, " +
            "  product_name, inoculant_name,  " +
            "  created_at, updated_at" +
            ") VALUES (" +
            "  #{productionOrderNo}, #{meltingTemperature}, #{inoculantAmount}, " +
            "  #{pouringTemperature}, #{qualificationRate}, #{productionTime}, " +
            "  #{batchNo}, #{inTime}, " +
            "  #{productName}, #{inoculantName}," +
            "  NOW(), NOW()" +
            ")")
    @Options(useGeneratedKeys = true, keyProperty = "orderId")
    void add(ProductionOrder productionOrder);

    @Insert("INSERT INTO production_order_details (" +
            "  order_id, batch_no, material_ratio, " +
            "  created_at, updated_at" +
            ") VALUES (" +
            "  #{orderId}, #{batchNo}, #{materialRatio}, " +
            "  NOW(), NOW()" +
            ")")
    void addDetail(ProductionOrderDetail detail);

    @Delete("DELETE FROM production_orders WHERE order_id = #{orderId}")
    void deleteById(Integer orderId);

    @Delete("DELETE FROM production_order_details WHERE order_id = #{orderId}")
    void deleteDetailsByOrderId(Integer orderId);

    //    @Update("<script>" +
//            "UPDATE production_orders " +
//            "<set>" +
//            "<if test='productionOrderNo != null'>production_order_no = #{productionOrderNo},</if>" +
//            "<if test='meltingTemperature != null'>melting_temperature = #{meltingTemperature},</if>" +
//            "<if test='inoculantAmount != null'>inoculant_amount = #{inoculantAmount},</if>" +
//            "<if test='pouringTemperature != null'>pouring_temperature = #{pouringTemperature},</if>" +
//            "<if test='qualificationRate != null'>qualification_rate = #{qualificationRate},</if>" +
//            "<if test='productionTime != null'>production_time = #{productionTime},</if>" +
//            "<if test='batchNo != null'>batch_no = #{batchNo},</if>" +
//            "<if test='inTime != null'>in_time = #{inTime},</if>" +
//            "updated_at = NOW()" +
//            "</set>" +
//            "WHERE order_id = #{orderId}" +
//            "</script>")
//    void update(ProductionOrder productionOrder);
    @Update("<script>" +
            "UPDATE production_orders " +
            "<set>" +
            "<if test='productionOrderNo != null'>production_order_no = #{productionOrderNo},</if>" +
            "<if test='meltingTemperature != null'>melting_temperature = #{meltingTemperature},</if>" +
            "<if test='inoculantAmount != null'>inoculant_amount = #{inoculantAmount},</if>" +
            "<if test='pouringTemperature != null'>pouring_temperature = #{pouringTemperature},</if>" +
            "<if test='qualificationRate != null'>qualification_rate = #{qualificationRate},</if>" +
            "<if test='productionTime != null'>production_time = #{productionTime},</if>" +
            "<if test='batchNo != null'>batch_no = #{batchNo},</if>" +
            "<if test='inTime != null'>in_time = #{inTime},</if>" +
            "<if test='productName != null'>product_name = #{productName},</if>" +
            "<if test='inoculantName != null'>inoculant_name = #{inoculantName},</if>" +
            "updated_at = NOW()" +
            "</set>" +
            "WHERE order_id = #{orderId}" +
            "</script>")
    void update(ProductionOrder productionOrder);

    //    @Results({
//            @Result(property = "orderId", column = "order_id"),
//            @Result(property = "productionOrderNo", column = "production_order_no"),
//            @Result(property = "batchNo", column = "batch_no"),
//            @Result(property = "meltingTemperature", column = "melting_temperature"),
//            @Result(property = "inoculantAmount", column = "inoculant_amount"),
//            @Result(property = "pouringTemperature", column = "pouring_temperature"),
//            @Result(property = "qualificationRate", column = "qualification_rate"),
//            @Result(property = "productionTime", column = "production_time"),
//            @Result(property = "inTime", column = "in_time"),
//            @Result(property = "createdAt", column = "created_at"),
//            @Result(property = "updatedAt", column = "updated_at"),
//            @Result(
//                    property = "details",
//                    column = "order_id",
//                    many = @Many(select = "com.minsu.mapper.ProductionOrdersMapper.findDetailsByOrderId")
//            )
//    })
//    @Select("SELECT * FROM production_orders WHERE order_id = #{orderId}")
//    ProductionOrder findById(Integer orderId);
    @Results({
            @Result(property = "orderId", column = "order_id"),
            @Result(property = "productionOrderNo", column = "production_order_no"),
            // 👇 新增以下两行
            @Result(property = "productName", column = "product_name"),
            @Result(property = "inoculantName", column = "inoculant_name"),
            @Result(property = "batchNo", column = "batch_no"),
            @Result(property = "meltingTemperature", column = "melting_temperature"),
            @Result(property = "inoculantAmount", column = "inoculant_amount"),
            @Result(property = "pouringTemperature", column = "pouring_temperature"),
            @Result(property = "qualificationRate", column = "qualification_rate"),
            @Result(property = "productionTime", column = "production_time"),
            @Result(property = "inTime", column = "in_time"),
            @Result(property = "createdAt", column = "created_at"),
            @Result(property = "updatedAt", column = "updated_at"),
            @Result(
                    property = "details",
                    column = "order_id",
                    many = @Many(select = "com.minsu.mapper.ProductionOrdersMapper.findDetailsByOrderId")
            )
    })
    @Select("SELECT * FROM production_orders WHERE order_id = #{orderId}")
    ProductionOrder findById(Integer orderId);

//    @Select("SELECT * FROM production_order_details " +
//           "WHERE order_id = #{orderId}")
//    List<ProductionOrderDetail> findDetailsByOrderId(Integer orderId);

    String getMaxBatchNoByDate(@Param("date") String date);


    // 添加批量更新炉料出库时间的方法
    @Update("<script>" +
            "UPDATE furnace_materials " +
            "SET out_time = #{productionTime} " +
            "WHERE batch_no IN " +
            "<foreach item='batch' collection='batchNos' open='(' separator=',' close=')'>" +
            "#{batch}" +
            "</foreach>" +
            "</script>")
    void updateOutTimeByBatchNos(@Param("batchNos") List<String> batchNos,
                                 @Param("productionTime") Date productionTime);

    // 插入主订单
    @Insert("<script>" +
            "INSERT INTO production_orders (" +
            "production_order_no, melting_temperature, inoculant_amount, pouring_temperature, " +
            "qualification_rate, production_time, batch_no, in_time, " +
            "product_name, inoculant_name, created_at, updated_at" +
            ") VALUES (" +
            "#{productionOrderNo}, #{meltingTemperature}, #{inoculantAmount}, #{pouringTemperature}, " +
            "#{qualificationRate}, #{productionTime}, #{batchNo}, #{inTime}, " +
            "#{productName}, #{inoculantName}, #{createdAt}, #{updatedAt}" +
            ")" +
            "</script>")
    @Options(useGeneratedKeys = true, keyProperty = "orderId", keyColumn = "order_id")
    void insert(ProductionOrder productionOrder);
}
